package com.xp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xp.entity.Menu;
import com.xp.service.MenuService;
import com.xp.utils.Result;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单管理控制器
 * 
 * @author xp
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/menus")
@RequiredArgsConstructor
public class MenuController {

    private static final Logger log = LoggerFactory.getLogger(MenuController.class);

    private final MenuService menuService;

    /**
     * 分页查询菜单列表
     * 
     * @param current 当前页
     * @param size 每页大小
     * @param name 菜单名称
     * @param status 菜单状态
     * @return 分页结果
     */
    @GetMapping("/page")
    public Result<IPage<Menu>> getMenuPage(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status) {
        try {
            Page<Menu> page = new Page<>(current, size);
            IPage<Menu> menuPage = menuService.getMenuPage(page, name, status);
            return Result.success(menuPage);
        } catch (Exception e) {
            log.error("分页查询菜单列表失败", e);
            return Result.error("查询菜单列表失败");
        }
    }

    /**
     * 获取所有启用的菜单
     * 
     * @return 菜单列表
     */
    @GetMapping("/enabled")
    public Result<List<Menu>> getEnabledMenus() {
        try {
            List<Menu> menus = menuService.getEnabledMenus();
            return Result.success(menus);
        } catch (Exception e) {
            log.error("获取启用菜单列表失败", e);
            return Result.error("获取菜单列表失败");
        }
    }

    /**
     * 获取菜单树
     * 
     * @return 菜单树
     */
    @GetMapping("/tree")
    public Result<List<Menu>> getMenuTree() {
        try {
            List<Menu> allMenus = menuService.getAllMenus();
            List<Menu> menuTree = menuService.buildMenuTree(allMenus);
            return Result.success(menuTree);
        } catch (Exception e) {
            log.error("获取菜单树失败", e);
            return Result.error("获取菜单树失败");
        }
    }

    /**
     * 根据父级菜单ID查询子菜单
     * 
     * @param parentId 父级菜单ID
     * @return 子菜单列表
     */
    @GetMapping("/children/{parentId}")
    public Result<List<Menu>> getMenusByParentId(@PathVariable Long parentId) {
        try {
            List<Menu> menus = menuService.getMenusByParentId(parentId);
            return Result.success(menus);
        } catch (Exception e) {
            log.error("根据父级菜单ID查询子菜单失败，父级ID: {}", parentId, e);
            return Result.error("查询子菜单失败");
        }
    }

    /**
     * 根据菜单类型查询菜单
     * 
     * @param type 菜单类型
     * @return 菜单列表
     */
    @GetMapping("/type/{type}")
    public Result<List<Menu>> getMenusByType(@PathVariable Integer type) {
        try {
            List<Menu> menus = menuService.getMenusByType(type);
            return Result.success(menus);
        } catch (Exception e) {
            log.error("根据菜单类型查询菜单失败，类型: {}", type, e);
            return Result.error("查询菜单失败");
        }
    }

    /**
     * 根据ID获取菜单详情
     * 
     * @param id 菜单ID
     * @return 菜单详情
     */
    @GetMapping("/{id}")
    public Result<Menu> getMenuById(@PathVariable Long id) {
        try {
            Menu menu = menuService.getById(id);
            if (menu == null) {
                return Result.error("菜单不存在");
            }
            return Result.success(menu);
        } catch (Exception e) {
            log.error("获取菜单详情失败，菜单ID: {}", id, e);
            return Result.error("获取菜单详情失败");
        }
    }

    /**
     * 创建菜单
     * 
     * @param menu 菜单信息
     * @return 操作结果
     */
    @PostMapping
    public Result<Object> createMenu(@RequestBody Menu menu) {
        try {
            boolean success = menuService.createMenu(menu);
            if (success) {
                return Result.success("菜单创建成功");
            } else {
                return Result.error("菜单创建失败");
            }
        } catch (Exception e) {
            log.error("创建菜单失败", e);
            return Result.error("创建菜单失败");
        }
    }

    /**
     * 更新菜单
     * 
     * @param id 菜单ID
     * @param menu 菜单信息
     * @return 操作结果
     */
    @PutMapping("/{id}")
    public Result<Object> updateMenu(@PathVariable Long id, @RequestBody Menu menu) {
        try {
            menu.setId(id);
            boolean success = menuService.updateMenu(menu);
            if (success) {
                return Result.success("菜单更新成功");
            } else {
                return Result.error("菜单更新失败");
            }
        } catch (Exception e) {
            log.error("更新菜单失败，菜单ID: {}", id, e);
            return Result.error("更新菜单失败");
        }
    }

    /**
     * 删除菜单
     * 
     * @param id 菜单ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public Result<Object> deleteMenu(@PathVariable Long id) {
        try {
            boolean success = menuService.deleteMenu(id);
            if (success) {
                return Result.success("菜单删除成功");
            } else {
                return Result.error("菜单删除失败，请检查是否存在子菜单");
            }
        } catch (Exception e) {
            log.error("删除菜单失败，菜单ID: {}", id, e);
            return Result.error("删除菜单失败");
        }
    }

    /**
     * 切换菜单状态
     * 
     * @param id 菜单ID
     * @param status 状态
     * @return 操作结果
     */
    @PutMapping("/{id}/status")
    public Result<Object> toggleMenuStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            boolean success = menuService.toggleMenuStatus(id, status);
            if (success) {
                return Result.success("菜单状态更新成功");
            } else {
                return Result.error("菜单状态更新失败");
            }
        } catch (Exception e) {
            log.error("切换菜单状态失败，菜单ID: {}, 状态: {}", id, status, e);
            return Result.error("切换菜单状态失败");
        }
    }
}